<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Services\TableMonitorService;

class MonitorBaoliaoTables extends Command
{
    protected $signature = 'baoliao:monitor-tables 
                            {--repair : 自动修复缺失的表}';
    protected $description = '监控爆料帖子分表的状态';
    
    public function handle()
    {
        $baseTable = 'baoliao_post';
        $monitorService = app(TableMonitorService::class);
        
        $this->info('开始检查分表状态...');
        
        $status = $monitorService->checkAllShardedTables($baseTable);
        
        // 显示热度分表状态
        $this->info("\n热度分表状态:");
        $this->table(
            ['表名', '存在', '行数', '最后更新', '大小(MB)'],
            collect($status['hot_tables'])->map(function($tableStatus, $tableName) {
                return [
                    'table' => $tableName,
                    'exists' => $tableStatus['exists'] ? '是' : '否',
                    'row_count' => $tableStatus['row_count'],
                    'last_updated' => $tableStatus['last_updated'] ?: '无数据',
                    'size' => $tableStatus['size']
                ];
            })->toArray()
        );
        
        // 显示时间分表状态
        $this->info("\n时间分表状态:");
        $this->table(
            ['表名', '存在', '行数', '最后更新', '大小(MB)'],
            collect($status['time_tables'])->map(function($tableStatus, $tableName) {
                return [
                    'table' => $tableName,
                    'exists' => $tableStatus['exists'] ? '是' : '否',
                    'row_count' => $tableStatus['row_count'],
                    'last_updated' => $tableStatus['last_updated'] ?: '无数据',
                    'size' => $tableStatus['size']
                ];
            })->toArray()
        );
        
        // 显示缺失的表
        if (!empty($status['missing_tables'])) {
            $this->error("\n缺失的表:");
            foreach ($status['missing_tables'] as $table) {
                $this->error(" - {$table}");
            }
            
            // 自动修复
            if ($this->option('repair')) {
                $this->info("\n开始自动修复缺失的表...");
                $repaired = $monitorService->repairMissingTables($baseTable);
                
                if (!empty($repaired)) {
                    $this->info("已修复的表:");
                    foreach ($repaired as $table) {
                        $this->info(" - {$table}");
                    }
                } else {
                    $this->info("没有需要修复的表");
                }
            }
        }
        
        $this->info("\n分表状态检查完成");
    }
}
